package com.qf.electronic.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;

import java.io.OutputStream;
import java.util.List;
import java.util.Map;

public abstract class AbstractExcelExporter<T> {

    private final Class<T> clazz;

    private final int perSheetCount;//每个sheet存放的数据量

    public AbstractExcelExporter(Class<T> clazz, int perSheetCount) {
        this.clazz = clazz;
        this.perSheetCount = perSheetCount;
    }

    //这个抽象方法主要作用就是用来查询导出的总条数
    protected abstract long getExportCount(Map<String, Object> params);
    //这个抽象方法主要作用就是用来查询导出的数据
    protected abstract List<T> getExportData(Map<String, Object> params, int page, int pageSize);

    public void export(Map<String, Object> params, OutputStream os, String sheetName){
        ExcelWriterBuilder writerBuilder = EasyExcel.write(os, clazz);
        ExcelWriter writer = writerBuilder.build();
        long total = getExportCount(params);//获取导出的总条数
        long sheetCount = total / perSheetCount;
        if(total % perSheetCount > 0){
            sheetCount ++;
        }
        for (int i=0; i<sheetCount; i++){
            WriteSheet sheet = new WriteSheet();
            sheet.setSheetNo(i);
            sheet.setSheetName(sheetName + (i+1));
            List<T> currentSheetData = getExportData(params,i+1, perSheetCount);
            writer.write(currentSheetData, sheet);
        }
        writer.finish();
    }
}
